package ca.cbc.gisdigester.digester;

import ca.cbc.feed.story.EptStory;
import ca.cbc.feed.story.EptStory.Video.TpClip;
import ca.cbc.giscommon.dao.CategoryDAO;
import ca.cbc.giscommon.entity.Category;
import ca.cbc.giscommon.entity.Story;
import ca.cbc.giscommon.util.GISConfig;
import ca.cbc.giscommon.util.GeometryUtil;
import ca.cbc.giscommon.util.StringUtil;
import ca.cbc.gisdigester.util.XmlHelper;
import com.vividsolutions.jts.geom.Geometry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenl
 * Date: 11/18/11
 * Time: 11:08 AM
 * To change this template use File | Settings | File Templates.
 */
public enum EptStoryDigester {
    instance;
    private Logger logger = LoggerFactory.getLogger(EptStoryDigester.class);
    private final String BASE_URL;
    
    EptStoryDigester() {
    	BASE_URL = GISConfig.instance.getProperty("base.url");
    }
    
    public Story digest(String feedFile) {
    	logger.info("**Digesting Ept Story file {}.", feedFile);
        Story story = null;
        try {	
            EptStory eptStory = XmlHelper.instance.<EptStory>digestXmlFile("ca.cbc.feed.story", new FileInputStream(feedFile));

            //get thumbnailUrl
            String thumbnailUrl = "";            
            if(eptStory.getImages() != null && !StringUtil.instance.isNullOrEmpty(eptStory.getImages().getTopStoryImage())) {
                String topStoryImage = eptStory.getImages().getTopStoryImage();
                thumbnailUrl = GISConfig.instance.getProperty("base.url") + topStoryImage;
            }
 
            //get Point Geometry theGoem
            Geometry geom = GeometryUtil.instance.parsePoint(eptStory.getLocation());
            
            //get category
            Category category = new CategoryDAO().findById(eptStory.getLocationCategory());
            
//            logger.debug("-----EptStory: " + eptStory.getId() + ", " + eptStory.getHeadline() + ", " + eptStory.getSummary()
//            		+ ", " + thumbnailUrl + ", " + eptStory.getRelativeUrl() + ", " + eptStory.getLocation() + ", " + eptStory.getType()
//            		+ ",*** " + eptStory.getLocalLocation() + ", " + eptStory.getSubcategory());
//            
//            for(TpClip clip : eptStory.getVideo().getTpClip()) {
//            	logger.debug("^^^" + clip.getId() + " " + clip.getType());
//            }
            
            //get audioClipIds and videoClipIds
            String audioClipIds = null;
            String videoClipIds = null;
            if(eptStory.getVideo() != null) {
            	List<TpClip> tpClips = eptStory.getVideo().getTpClip();
            	if(tpClips != null && !tpClips.isEmpty()) {
            		for(TpClip clip : tpClips) {
            			if(clip.getType().equalsIgnoreCase("video")) {
            				videoClipIds = clip.getId() + ",";
            			} else if(clip.getType().equalsIgnoreCase("audio")) {
            				audioClipIds = clip.getId() + ",";
            			}
            		}
            		if(audioClipIds != null && audioClipIds.endsWith(",")) {
            			audioClipIds = audioClipIds.substring(0, audioClipIds.length()-1);
            		}
            		if(videoClipIds != null && videoClipIds.endsWith(",")) {
            			videoClipIds = videoClipIds.substring(0, videoClipIds.length()-1);
            		}
            	}
            }
            boolean cbcContent = true;
            String storyUrl = eptStory.getRelativeUrl();
            if(storyUrl.startsWith("/")){
            	storyUrl = BASE_URL + storyUrl;
            } else if (!storyUrl.toLowerCase().contains("cbc.c")) {
            	cbcContent = false;
            }
            
            story = new Story(eptStory.getId(), eptStory.getHeadline(), eptStory.getSummary(), thumbnailUrl,
            		eptStory.getPageFlag(), storyUrl,
                    eptStory.getPostedTime().getDateInSeconds() * 1000l,
            		eptStory.getLastUpdatedTime().getDateInSeconds() * 1000l, geom, category, videoClipIds,
                    audioClipIds, eptStory.getAuthorBio(), cbcContent);
            
        } catch (JAXBException e) {
            logger.error("JAXBException.", e);
        } catch (FileNotFoundException e) {
            logger.error("File {} not found.", feedFile, e);
        } catch (Exception e) {
            logger.error("Exception when digesting feed file.", e);
        }
        //logger.debug("^Digested story is {}", story);
        logger.info("**Etp Story file {} digested.", feedFile);
        return story;
    }
}
